document.addEventListener('DOMContentLoaded', () => {
    // DOM元素引用
    const scanBtn = document.getElementById('scan-btn');
    const statusText = document.getElementById('status-text');
    const devicesList = document.getElementById('devices-list');
    const deviceCount = document.getElementById('device-count');
    const connectedDevice = document.getElementById('connected-device');
    const deviceInfo = document.getElementById('device-info');
    const disconnectBtn = document.getElementById('disconnect-btn');
    const browserAlert = document.getElementById('browser-alert');
    
    // 检查浏览器是否支持Web Bluetooth API
    if (!navigator.bluetooth) {
        browserAlert.classList.remove('hidden');
        scanBtn.disabled = true;
        scanBtn.classList.add('bg-gray-400', 'cursor-not-allowed', 'hover:scale-100');
        scanBtn.innerHTML = '<i class="fa fa-ban mr-2"></i>浏览器不支持蓝牙';
    }
    
    // 存储已发现的设备和已连接的设备
    let discoveredDevices = [];
    let connectedDeviceObj = null;
    let gattServer = null;
    
    // 扫描蓝牙设备
    scanBtn.addEventListener('click', async () => {
        try {
            updateStatus('正在请求蓝牙权限...', 'info');
            scanBtn.disabled = true;
            scanBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>扫描中...';
            
            // 重置设备列表
            discoveredDevices = [];
            devicesList.innerHTML = '<div class="text-center py-6"><i class="fa fa-spinner fa-spin text-primary text-2xl"></i><p class="mt-2 text-gray-500">正在扫描蓝牙设备...</p></div>';
            
            // 请求蓝牙设备
            // 这里使用了通用属性配置文件，可以根据需要修改过滤器
            const device = await navigator.bluetooth.requestDevice({
                acceptAllDevices: true,
                optionalServices: [
                    '00001800-0000-1000-8000-00805f9b34fb', // 设备信息服务
                    '00001801-0000-1000-8000-00805f9b34fb'  // 通用属性服务
                ]
            });
            
            // 监听设备断开连接事件
            device.addEventListener('gattserverdisconnected', handleDisconnection);
            
            // 添加到设备列表
            discoveredDevices.push(device);
            updateDeviceList();
            updateStatus(`发现 ${discoveredDevices.length} 个蓝牙设备`, 'success');
            
        } catch (error) {
            console.error('蓝牙扫描错误:', error);
            
            // 常见错误处理
            if (error.name === 'NotFoundError') {
                updateStatus('未找到蓝牙设备，请确保设备已开启', 'error');
            } else if (error.name === 'NotAllowedError') {
                updateStatus('蓝牙权限被拒绝，请在浏览器设置中允许', 'error');
            } else {
                updateStatus(`扫描失败: ${error.message}`, 'error');
            }
            
            resetScanButton();
        }
    });
    
    // 断开连接按钮事件
    disconnectBtn.addEventListener('click', async () => {
        if (gattServer) {
            gattServer.disconnect();
            handleDisconnection();
        }
    });
    
    // 更新状态文本
    function updateStatus(message, type = 'info') {
        statusText.textContent = message;
        
        // 设置状态文本颜色
        statusText.className = 'mt-4';
        switch(type) {
            case 'success':
                statusText.classList.add('text-secondary');
                break;
            case 'error':
                statusText.classList.add('text-danger');
                break;
            case 'info':
            default:
                statusText.classList.add('text-gray-600');
                break;
        }
    }
    
    // 更新设备列表
    function updateDeviceList() {
        if (discoveredDevices.length === 0) {
            devicesList.innerHTML = '<div class="text-gray-500 text-center py-8 border border-dashed border-gray-200 rounded-lg"><i class="fa fa-bluetooth-b text-4xl mb-3 text-gray-300"></i><p>未发现任何蓝牙设备</p></div>';
            deviceCount.textContent = '0';
            resetScanButton();
            return;
        }
        
        deviceCount.textContent = discoveredDevices.length;
        devicesList.innerHTML = '';
        
        discoveredDevices.forEach(device => {
            const deviceCard = document.createElement('div');
            deviceCard.className = 'device-card';
            
            // 设备名称处理
            const deviceName = device.name || '未知设备';
            // 设备ID截断显示
            const shortId = device.id.substring(0, 8) + '...';
            
            deviceCard.innerHTML = `
                <div class="flex justify-between items-start">
                    <div>
                        <h3 class="font-medium text-dark">${deviceName}</h3>
                        <p class="text-sm text-gray-500 mt-1">
                            <i class="fa fa-microchip mr-1"></i>
                            ID: ${shortId}
                        </p>
                        <p class="text-xs text-gray-400 mt-2">
                            ${device.gatt.connected ? 
                                '<span class="status-indicator bg-secondary"></span>已连接' : 
                                '<span class="status-indicator bg-gray-300"></span>未连接'}
                        </p>
                    </div>
                    <button class="connect-btn ${device.gatt.connected ? 'hidden' : ''}" 
                            data-device-id="${device.id}">
                        <i class="fa fa-plug mr-1"></i>连接
                    </button>
                </div>
            `;
            
            devicesList.appendChild(deviceCard);
        });
        
        // 为连接按钮添加事件监听
        document.querySelectorAll('.connect-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const deviceId = e.currentTarget.dataset.deviceId;
                const device = discoveredDevices.find(d => d.id === deviceId);
                if (device) {
                    connectToDevice(device);
                }
            });
        });
        
        resetScanButton();
    }
    
    // 连接到蓝牙设备
    async function connectToDevice(device) {
        try {
            updateStatus(`正在连接到 ${device.name || '未知设备'}...`, 'info');
            
            // 连接到GATT服务器
            gattServer = await device.gatt.connect();
            connectedDeviceObj = device;
            
            // 获取设备信息服务
            const deviceInfoService = await gattServer.getPrimaryService('00001800-0000-1000-8000-00805f9b34fb');
            
            // 读取设备信息特征
            const deviceNameChar = await deviceInfoService.getCharacteristic('00002a00-0000-1000-8000-00805f9b34fb');
            const modelNumberChar = await deviceInfoService.getCharacteristic('00002a01-0000-1000-8000-00805f9b34fb');
            
            const deviceName = await deviceNameChar.readValue();
            const modelNumber = await modelNumberChar.readValue();
            
            // 转换为字符串
            const name = new TextDecoder().decode(deviceName);
            const model = new TextDecoder().decode(modelNumber) || '未知型号';
            
            // 显示设备信息
            showDeviceInfo(device, name, model);
            
            updateStatus(`已成功连接到 ${name}`, 'success');
            updateDeviceList();
            
        } catch (error) {
            console.error('设备连接错误:', error);
            updateStatus(`连接失败: ${error.message}`, 'error');
        }
    }
    
    // 显示已连接设备信息
    function showDeviceInfo(device, name, model) {
        connectedDevice.classList.remove('hidden');
        
        deviceInfo.innerHTML = `
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <h3 class="text-lg font-medium text-dark">${name}</h3>
                    <p class="text-gray-600 text-sm mt-1">型号: ${model}</p>
                    <p class="text-gray-500 text-xs mt-2">设备ID: ${device.id}</p>
                </div>
                <div class="text-right">
                    <span class="inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">
                        <i class="fa fa-check-circle mr-1"></i>已连接
                    </span>
                    <p class="text-gray-500 text-xs mt-2">连接时间: ${new Date().toLocaleTimeString()}</p>
                </div>
            </div>
            
            <div class="mt-4 pt-4 border-t border-gray-100">
                <h4 class="font-medium text-gray-700 mb-2">可用服务</h4>
                <div id="device-services" class="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    <!-- 服务信息将动态加载 -->
                    <div class="bg-gray-50 p-2 rounded text-sm text-gray-600">
                        <i class="fa fa-cog mr-1 text-primary"></i>设备信息服务
                    </div>
                    <div class="bg-gray-50 p-2 rounded text-sm text-gray-600">
                        <i class="fa fa-exchange mr-1 text-primary"></i>通用属性服务
                    </div>
                </div>
            </div>
        `;
    }
    
    // 处理设备断开连接
    function handleDisconnection() {
        if (connectedDeviceObj) {
            updateStatus(`已与 ${connectedDeviceObj.name || '未知设备'} 断开连接`, 'info');
            connectedDeviceObj = null;
            gattServer = null;
        } else {
            updateStatus('蓝牙设备已断开连接', 'info');
        }
        
        connectedDevice.classList.add('hidden');
        updateDeviceList();
    }
    
    // 重置扫描按钮状态
    function resetScanButton() {
        scanBtn.disabled = false;
        scanBtn.innerHTML = '<i class="fa fa-search mr-2"></i>开始蓝牙扫描';
    }
});
